package top.yamhk.agent.entity.dto;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ZipUtil;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
@Getter
public class Felicity {
    public static final String fileSepLinux = "/";
    public static final String wsTransHk = "/tmp/hk/";
    public static final String dataSpace = "/tmp/hk/mxDBs/";
    public static final String tranSpace = "/root/hk/trans/";
    public static final String wsTransO3 = "/root/hk/trans/20221201_00_00_00_0/V/";
    public static final String wsTransO2 = "/root/hk/trans/20221201_00_00_00_0/OO/";
    public static final String wsTransO1 = "/root/hk/trans/20221201_00_00_00_0/O/";
    public static final String wsTransI2 = "/root/hk/trans/20221201_00_00_00_0/II/";
    public static final String wsTransI1 = "/root/hk/trans/20221201_00_00_00_0/I/";
    public static boolean dis = false;
    public static boolean yy = false;
    public static int count = 0;
    public static String currentSpit = "z";
    public static String encode = "utf-8";
    public static String encodeIso = "ISO-8859-1";
    public static Map<String, byte[]> tpMap = new TreeMap<>();
    public static Map<String, Object> hxMap = new HashMap<>();
    private static final String homeProfile = doGetValue(System.getProperty("user.home"), "") + "/";
    public static final String workspace = homeProfile + "workspace";
    public static final String demoSpace = homeProfile + "workspace/demo";
    public static final String pubMatrix = homeProfile + "workspace/demo/matrix_public/";
    public static final String wsMxCloud = homeProfile + "workspace/demo/matrix_cloud/";
    public static final String wsWebView = homeProfile + "workspace/demo/matrix_html/";
    public static final String wsUniView = homeProfile + "workspace/demo/matrix_app/";
    public static final String wsAtDevDY = homeProfile + "workspace/demo_mwcprs/";
    public static final String wsAtDevDM = homeProfile + "workspace/demo_mf/";

    public static File getTranslateFile() {
        return new File(tranSpace + "/data_4_translate.txt");
    }

    public static String doGetValue(String key, String value) {
        if (hxMap == null) {
            hxMap = new HashMap<>(25);
        }
        if (StringUtils.isEmpty(value)) {
            String path = hxMap == null || hxMap.get(key) == null ? key : (String) hxMap.get(key);
            path = path.replaceAll("\\\\", fileSepLinux);
            path = path.replaceAll("//", fileSepLinux);
            hxMap.put(key, path);
            return path;
        }
        hxMap.put(key, value);
        return (String) hxMap.get(key);
    }

    public static String getInputMatrix(String dir) {
        final String path = pubMatrix + (!StringUtils.isEmpty(dir) ? dir : "");
        return getPathAfterCreate(path);
    }

    public static String getBzMatrix(String dir) {
        final String path = wsTransO3 + (!StringUtils.isEmpty(dir) ? dir : "");
        return getPathAfterCreate(path);
    }

    public static String getOutputMatrix(String dir) {
        final String path = wsTransO1 + (!StringUtils.isEmpty(dir) ? dir : "");
        return getPathAfterCreate(path);
    }

    private static String getPathAfterCreate(String path) {
        new File(path).mkdirs();
        String matrix = path;
        matrix = matrix.replaceAll("\\\\", File.separator);
        return matrix;
    }

    @SneakyThrows
    public static void asQrReader(String strFromImage) {
        String[] split;
        currentSpit = String.valueOf(strFromImage.charAt(5));
        //judge
        if (StringUtils.isEmpty(strFromImage) || (split = strFromImage.split(currentSpit)).length < 4) {
            log.error("error file-[{}]", strFromImage);
            return;
        }
        //组装
        String gzipPage = split[0];
        String gzip = gzipPage.substring(0, 1);
        String paBg = gzipPage.substring(1, 3);
        String paEg = gzipPage.substring(3, 5);
        String name = new String(ZipUtil.unGzip(split[1].getBytes(encodeIso)));
        String pack = new String(ZipUtil.unGzip(split[2].getBytes(encodeIso)));
        String content = split[3];
        log.error("[{}]-[{}]-[{}]-[{}]-[{}]", "BEST", currentSpit, gzipPage, name, content.length());
        tpMap.put(name + gzipPage, content.getBytes(encodeIso));
        if (tpMap.size() == Integer.valueOf(paEg)) {
            byte[] out = new byte[0];
            for (Map.Entry<String, byte[]> entry : tpMap.entrySet()) {
                out = ArrayUtils.addAll(out, entry.getValue());
            }
            File targetFile = new File(getOutputMatrix("/" + pack) + name);
            log.trace("[{}]", targetFile.getAbsolutePath());
            tpMap.clear();
            FileUtil.writeUtf8String(new String(ZipUtil.unGzip(out)), targetFile);
            log.info("transfer ok-[{}]", name);
        }
    }

    public static String randomId() {
        String acId = "";
        acId = "151";
        acId = String.valueOf(RandomUtil.randomInt(2));
        acId = String.valueOf(RandomUtil.randomInt(99_000));
        return acId;
    }
//
//    @SneakyThrows
//    public static String domainNameSystem() {
//        String resolver = "";
//        final SimpleResolver simpleResolver = new SimpleResolver("12.99.200.12");
//        simpleResolver.setPort(53);
//        final Lookup lookup = new Lookup("dev.nbcb.com", Type.A);
//        lookup.setResolver(simpleResolver);
//        lookup.run();
//        log.warn("[{}]", lookup);
//        System.out.println(lookup.getResult());
//        System.out.println(lookup.getAnswers()[0].rdataToString());
//        resolver = resolver();
//        return resolver;
//    }
//
//    public static String resolver() {
//        int port = 53;
//        byte[] buffer = new byte[2048];
//        try (DatagramSocket socket = new DatagramSocket(port)) {
//            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//            while (SubDemoApp.dns) {
//                try {
//                    socket.receive(packet);
//                    final Message qryData = new Message(packet.getData());
//                    log.trace("==>[{}]", qryData);
//                    final String domain = qryData.getQuestion().getName().toString();
//                    final InetAddress byName = Address.getByName(domain);
//                    //response
//                    final Message ansData = (Message) qryData.clone();
//                    final ARecord aRecord = new ARecord(qryData.getQuestion().getName(), qryData.getQuestion().getDClass(), 64, byName);
//                    ansData.addRecord(aRecord, Section.ANSWER);
//                    final byte[] bytes = ansData.toWire();
//                    final DatagramPacket response = new DatagramPacket(bytes, bytes.length, packet.getAddress(), packet.getPort());
//                    socket.send(response);
//                } catch (Exception e) {
//                    log.trace("[{}]-[{}]", SubDemoApp.DIVISION, e.getMessage());
//                }
//            }
//        } catch (SocketException e) {
//            log.error("[{}]-[{}]", SubDemoApp.DIVISION, e.getMessage());
//        }
//        return "ok";
//    }
}
